<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单名称" prop="orderName">
              <el-input v-model="queryParams.orderName" placeholder="请输入订单名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="queryParams.orderStatus" placeholder="订单状态" clearable>
                <el-option v-for="dict in sys_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单来源" prop="orderSource">
              <el-select v-model="queryParams.orderSource" placeholder="订单来源" clearable>
                <el-option v-for="dict in sys_order_source" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleImport" v-hasPermi="['system:orderSalesData:import']">导入数据</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="orderSalesDataList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="记录ID" align="center" prop="id" v-if="true" />-->
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <el-table-column label="订单编号" align="center">
          <template #default="scope">
            <span>系统单号: {{ scope.row.systemOrderNumber }}</span><br>
            <span>外部单号: {{ scope.row.externalOrderNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单名称" align="center" prop="orderName" />
        <el-table-column prop="orderSource" label="订单来源" width="80">
          <template #default="scope">
            <dict-tag :options="sys_order_source" :value="scope.row.orderSource" />
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态"  width="80">
          <template #default="scope">
            <dict-tag :options="sys_order_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <el-table-column label="订单状态描述" align="center" prop="statusDescription" />
        <el-table-column label="身份证信息" align="center">
          <template #default="scope">
            <span>身份证名: {{ scope.row.idCardName }}</span><br>
            <span>身份证号: {{ scope.row.idCardNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货信息" align="center">
          <template #default="scope">
            <span>收件人: {{ scope.row.recipient }}</span><br>
            <span>联系电话: {{ scope.row.contactPhoneNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货地址" align="center">
          <template #default="scope">
            {{ scope.row.province }}{{ scope.row.city }}{{ scope.row.districtCounty }}{{ scope.row.shippingAddress }}
          </template>
        </el-table-column>
        <el-table-column label="转单信息" align="center">
          <template #default="scope">
            <span>转单标记: {{ scope.row.transferOrderMark }}</span><br>
            <span>转单时间: {{ scope.row.transferOrderTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物流信息" align="center">
          <template #default="scope">
            <span>物流单号: {{ scope.row.logisticsOrderNumber }}</span><br>
            <span>物流名称: {{ scope.row.logisticsName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="creationTime">
          <template #default="scope">
            <span>{{ scope.row.creationTime }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderSalesData" lang="ts">
import { listOrderSalesData, getOrderSalesData, delOrderSalesData, addOrderSalesData, updateOrderSalesData } from '@/api/company/orderSalesData';
import { OrderSalesDataVO, OrderSalesDataQuery, OrderSalesDataForm } from '@/api/company/orderSalesData/types';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const orderSalesDataList = ref<OrderSalesDataVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const orderSalesDataFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/system/orderSalesData/importData'
});

const { sys_order_status, sys_order_source } = toRefs<any>(proxy?.useDict('sys_order_status', 'sys_order_source'));

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderSalesDataForm = {
  id: undefined,
  systemOrderNumber: undefined,
  orderName: undefined,
  merchant: undefined,
  supplierName: undefined,
  productCode: undefined,
  commodityCode: undefined,
  orderStatus: undefined,
  statusDescription: undefined,
  orderSource: undefined,
  idCardName: undefined,
  idCardNumber: undefined,
  recipient: undefined,
  contactPhoneNumber: undefined,
  province: undefined,
  city: undefined,
  districtCounty: undefined,
  shippingAddress: undefined,
  storeName: undefined,
  externalOrderNumber: undefined,
  extendedOrderNumber: undefined,
  transferOrderMark: undefined,
  transferOrderTime: undefined,
  logisticsOrderNumber: undefined,
  logisticsName: undefined,
  activationNumber: undefined,
  shippingTime: undefined,
  activationTime: undefined,
  firstRechargeTime: undefined,
  creationTime: undefined,
  remarks: undefined,
  lastUpdateTime: undefined,
  commissionSettlementStatus: undefined,
  commissionSettlementAmount: undefined,
  topLevelSupplierName: undefined,
  liveStreamerId: undefined,
  liveStreamerName: undefined,
  commodityType: undefined,
  cardOpeningNumberPlaceOfOrigin: undefined
}
const data = reactive<PageData<OrderSalesDataForm, OrderSalesDataQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    systemOrderNumber: undefined,
    orderName: undefined,
    merchant: undefined,
    supplierName: undefined,
    productCode: undefined,
    commodityCode: undefined,
    orderStatus: undefined,
    statusDescription: undefined,
    orderSource: undefined,
    idCardName: undefined,
    idCardNumber: undefined,
    recipient: undefined,
    contactPhoneNumber: undefined,
    province: undefined,
    city: undefined,
    districtCounty: undefined,
    shippingAddress: undefined,
    storeName: undefined,
    externalOrderNumber: undefined,
    extendedOrderNumber: undefined,
    transferOrderMark: undefined,
    transferOrderTime: undefined,
    logisticsOrderNumber: undefined,
    logisticsName: undefined,
    activationNumber: undefined,
    shippingTime: undefined,
    activationTime: undefined,
    firstRechargeTime: undefined,
    creationTime: undefined,
    remarks: undefined,
    lastUpdateTime: undefined,
    commissionSettlementStatus: undefined,
    commissionSettlementAmount: undefined,
    topLevelSupplierName: undefined,
    liveStreamerId: undefined,
    liveStreamerName: undefined,
    commodityType: undefined,
    cardOpeningNumberPlaceOfOrigin: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "记录ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单销售数据信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrderSalesData(proxy?.addDateRange(queryParams.value, dateRange.value));
  orderSalesDataList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  orderSalesDataFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderSalesDataVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}



/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户导入';
  upload.open = true;
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(() => {
  getList();
});
</script>
